﻿using Apps.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Apps.Repository.UnitOfWork
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly SqlDbContext _context;

        private bool disposed = false;
        private readonly ConcurrentDictionary<Type, object> _repository;


        public UnitOfWork(SqlDbContext context)
        {
            _context = context;
            _repository = new ConcurrentDictionary<Type, object>();
        }

        public IBaseRepository<TEntity, TKey> GetRepository<TEntity, TKey>() where TEntity : class, IEntity<TKey>
        {
            return (IBaseRepository<TEntity, TKey>)_repository.GetOrAdd(
                typeof(TEntity),
                t => new BaseRepository<TEntity, TKey>(_context)
            );
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            _context.Dispose();
            GC.SuppressFinalize(this);
        }


        public async Task<int> SaveChangesAsync()
        {
            return await _context.SaveChangesAsync();
        }

        public async Task BeginTranAsync()
        {
            if (_context.Database.CurrentTransaction == null)
            {
                await _context.Database.BeginTransactionAsync();
            }

        }

        public async Task CommitTranAsync()
        {
            try
            {
                await _context.Database.CommitTransactionAsync();
            }
            catch (Exception ex)
            {
                await _context.Database.RollbackTransactionAsync();
                throw;
            }

        }

        public async Task RollbackTranAsync()
        {
            await _context.Database.RollbackTransactionAsync();
        }
    }
}
